package com.example.webbrowser.Utils;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * 重写 WebViewClient
 */
public class MyWebViewClient extends WebViewClient {

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        view.getSettings().setJavaScriptEnabled(true);
        super.onPageStarted(view, url, favicon);
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public void onPageFinished(WebView view, String url) {
        view.getSettings().setJavaScriptEnabled(true);
        super.onPageFinished(view, url);
        addImageClickListener(view);  //待网页加载完全后设置图片点击的监听方法
    }

    private void addImageClickListener(WebView view) {
        view.loadUrl("javascript:(function(){"
                +"var objs = document.getElementsByTagName(\"img\"); "
                +"window.imagelistener.setNewArray();"
                +"var Expression=/https:\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- .\\/?%&=]*)?/;"
                +"var objExp=new RegExp(Expression);"
                +"var array=new Array();"
                +"var j = 0;"
                + "for(var i=0;i<objs.length;i++)"
                +"{"
                +   "if(objExp.test(objs[i].src))"
                +  "{"
                +    "array[j++] = objs[i];"
                +  "   window.imagelistener.showSource(objs[i].src);  "
                +   "}"
                +"}"
                // "window.imagelistener.showSource(document.getElementsByTagName('html')[0].innerHTML);"
                +"for(var i=0;i<array.length;i++)  "
                +"{"
                + "    array[i].onclick=function()  "
                +"    {  "
                //  +       "var Expression2=/https:\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- .\\/?%&=]*)?/;"
                // +       " var objExp2=new RegExp(Expression);"
                +       "if(objExp.test(this.src))"
                +       "{"
                +           "window.imagelistener.openImage(this.src);  "
                +       "}"
                +"    }  " +
                "}" +
                "})()");
    }
}
